﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPatternDemoCApp.Creational
{
    /// <summary>
    /// 单例模式
    /// 保证一个类仅有一个实例，并提供一个该实例的全局访问点
    /// </summary>
    public class Singleton
    {
        private static readonly Lazy<Singleton> _Instance_New = new Lazy<Singleton>();

        private static Singleton _Instance;

        private static readonly object locker=new object();

        /// <summary>
        /// 私有静态构造函数防止外部New
        /// </summary>
        static Singleton()
        {

        }

        /// <summary>
        /// 新版本单例
        /// </summary>
        public static Singleton Instance_New
        {
            get
            {
                //Lazy,线程安全,并且只在第一次获取时才创建
                return _Instance_New.Value;
            }
        }

        /// <summary>
        /// 对外公开获取实例
        /// </summary>
        public static Singleton Instance
        {
            get
            {
                if (_Instance == null)
                {
                    lock (locker)
                    {
                        //这个地方进行二次判断是有必要的,防止多线程重复创建
                        if (_Instance==null)
                        {
                            _Instance = new Singleton();
                        }
                    }
                }
                return _Instance;
            }
        }

    }
}
